#!/usr/bin/env perl

use strict;
use warnings;
use v5;

my $max_loop = 1000;

sub show_usage;
sub gen_file_name;

my $orig_dir = $ARGV[0];
my $dest_dir = $ARGV[1];

show_usage unless $orig_dir;
show_usage unless $dest_dir;

print STDERR "orig_dir = $orig_dir\n";
print STDERR "dest_dir = $dest_dir\n";

my $orig_data = join '/', $orig_dir, 'data.bkmk';

print STDERR "orig_data = $orig_data\n";

if (-r $orig_data) {

  if (not -d $dest_dir) {

    print STDERR "Creating $dest_dir\n";

    mkdir $dest_dir;

  }

  open my $ofh, '<', $orig_data or die "Could not open $orig_data: $!";

  while (<$ofh>) {

    my $line = $_;

    chomp $line;

    my @line_items = split ' ', $line;

    my $url_name = shift @line_items;

    my $url_href = join ' ', @line_items;

    print STDERR "  url_name = $url_name\n";

    $url_name =~ s/_/ /g;

    print STDERR "             $url_name\n";

    print STDERR "  url_href = $url_href\n";

    my $dest_file_name = gen_file_name;

    my $dest_file = join '/', $dest_dir, $dest_file_name . '.bkmk';

    my $loop_no = 0;

    while (-e $dest_file and $loop_no < $max_loop) {

      $dest_file_name = gen_file_name;

      $dest_file = join '/', $dest_dir, $dest_file_name . '.bkmk';

      $loop_no++;

    }

    print STDERR "  dest_file = $dest_file\n";

    if (-e $dest_file) {

      print STDERR "Could not create a unique dest file name\n";

      exit 1;

    }

    open my $dfh, '>', $dest_file or die "Could not open $dest_file: $!";

    print $dfh "BKMK_FILE\n";
    print $dfh "$url_name\n";
    print $dfh "$url_href\n";

    close $dfh;

  }

  close $ofh;

} else {

  print STDERR "Can not read $orig_data\n";

  exit 1;

}

exit 0;

sub show_usage {

  print STDERR <<EOM;
Usage: $0 orig_dir dest_dir
EOM

  exit 1;

}

sub gen_file_name {

  my @chars = qw/a b c d e f g h i j k l m n o p q r s t u v w x y z
               A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
               0 1 2 3 4 5 6 7 8 9/;

  my $rand_string_size = 8;
  my $rand_s = '';

  for (my $i = 0; $i < $rand_string_size; $i++) {

    my $char_id = int (rand ($#chars + 1));

    $rand_s .= $chars[$char_id];

  }

  return $rand_s;

}
